package com.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;

public class FileUpload {
	/**
	 * 
	 * @param file 
	 * @param fileNames
	 * @param toPath the real path to store the files
	 * @param serverPath be used to display the file in the page
	 * @throws IOException
	 */
	public static List<String> Upload(List<File> file,List<String> fileNames, String toPath,String serverPath) throws IOException{
		List<String> uploadedFiles = new ArrayList<String>();
		for (int i = 0; i < file.size(); ++i)
		{
			InputStream is = new FileInputStream(file.get(i));

//			String root = ServletActionContext.getServletContext().getRealPath(
//					"/product-pic");

			File destFile = new File(toPath, fileNames.get(i));

			OutputStream os = new FileOutputStream(destFile);

			byte[] buffer = new byte[400];

			int length = 0;

			while ((length = is.read(buffer)) > 0)
			{
				os.write(buffer, 0, length);
			}

			is.close();

			os.close();
			uploadedFiles.add(serverPath+fileNames.get(i));
		}
		return uploadedFiles;

	}
}
